package com.gaogzhen.security.activity;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * 哲学家类
 */
@Slf4j(topic = "c.Philosopher")
@Data
public class Philosopher extends Thread{
    /** 左手边筷子名称 */
    private Chopstick left;
    /** 右手边筷子名称 */
    private Chopstick right;

    public Philosopher(String name, Chopstick left, Chopstick right) {
        super(name);
        this.left = left;
        this.right = right;
    }

    @Override
    public void run() {
        while (true) {
            // 尝试获取左手边的筷子
            synchronized (left) {
                // 尝试后去右手边的筷子
                synchronized (right) {
                    // 吃饭
                    eat();
                }
            }
        }
    }

    /**
     * 吃饭
     */
    private void eat() {
        log.debug("eating ...");
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
